package cn.seocoo.platform.common.utils.upload;


import com.aliyun.vod.upload.impl.UploadImageImpl;
import com.aliyun.vod.upload.req.UploadImageRequest;
import com.aliyun.vod.upload.resp.UploadImageResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.File;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class AliyunVOD {
    private static final Logger log = LoggerFactory.getLogger(AliyunVOD.class);


    /**视频保存路径 */
    public static String saveVideoPath;
    @Value("${save.api.video.path}")
    public void setSaveVideoPath(String saveVideoPath) {
        AliyunVOD.saveVideoPath = saveVideoPath;
    }

    /**图片保存路径 */
    public static String saveImagePath;
    @Value("${save.api.image.path}")
    public void setSaveImagePath(String saveImagePath) {
        AliyunVOD.saveImagePath = saveImagePath;
    }



    /**账号AK信息请填写(必选) */
    public static String accessKeyId;
    @Value("${aliyun.accessKeyId}")
    public void setAccessKeyId(String accessKeyId) {
        AliyunVOD.accessKeyId = accessKeyId;
    }

    /**账号AK信息请填写(必选) */
    public static String accessKeySecret;
    @Value("${aliyun.accessKeySecret}")
    public void setAccessKeySecret(String accessKeySecret) {
        AliyunVOD.accessKeySecret = accessKeySecret;
    }

    /** 转码模版 */
    public static String templateGroupId;
    @Value("${aliyun.templateGroupId}")
    public void setTemplateGroupId(String templateGroupId) {
        AliyunVOD.templateGroupId = templateGroupId;
    }

    /**
     * 阿里云初始化
     * @author duanpj
     * @return
     */
    public static DefaultAcsClient initVodClient(){
        String regionId = "cn-shanghai";  // 点播服务接入区域
        DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        return client;
    }

    /**
     * 阿里云：获取视频播放地址
     * @author duanpj
     * @param videoId
     * @return
     */
    public static Map getVideoPlayUrl(String videoId){
        DefaultAcsClient client = initVodClient();
        GetPlayInfoRequest request = new GetPlayInfoRequest();
        GetPlayInfoResponse response;
        request.setVideoId(videoId);
        String playUrl;
        Map map = new HashMap();
        try {
            response = client.getAcsResponse(request);
            List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();
            if(playInfoList != null && playInfoList.size() > 0 ){
                playUrl = response.getPlayInfoList().get(0).getPlayURL();
                map.put("playUrl",playUrl);
                log.info("PlayInfo.PlayURL = " + playUrl);
            }
        } catch (Exception e) {
            log.error("getVideoPlayUrl--->ErrorMessage = " + e.getLocalizedMessage());
        }
        return map;
    }

    /**
     * 获取阿里云图片信息
     * @param imageId
     * @return
     */
    public static Map getImageUrl(String imageId){
        DefaultAcsClient client = initVodClient();
        GetImageInfoRequest request = new GetImageInfoRequest();
        GetImageInfoResponse response;
        request.setImageId(imageId);
        String imageUrl;
        Map map = new HashMap();
        try {
            response = client.getAcsResponse(request);
            imageUrl = response.getImageInfo().getMezzanine().getFileURL();
            map.put("imageUrl", imageUrl);
            log.info("imageUrl = " + imageUrl);
        } catch (Exception e) {
            log.error("getImageUrl--->ErrorMessage = " + e.getLocalizedMessage());
        }
        return map;
    }


    /**
     * 上传视频封面至阿里云媒体库
     * @author duanpj
     * @param fileName 本地图片的绝对路径
     * @param videoName 图片的标题(和视频标题保持一致)
     * @return
     */
    public static Map imageUploadStream(String fileName,String videoName) {
        /* 图片类型（必选）取值范围：default（默认)，cover（封面），watermark（水印）*/
        /** 控制台暂时只支持default类型的图片管理，其他的还需要通过API来管理。 */
        String imageType = "default";
        UploadImageRequest request = new UploadImageRequest(accessKeyId, accessKeySecret, imageType);
        request.setImageType("default");
        request.setFileName(fileName);
        /* 图片标题（可选）长度不超过128个字节，UTF8编码 */
        request.setTitle(videoName);
        UploadImageImpl uploadImage = new UploadImageImpl();
        UploadImageResponse response = uploadImage.upload(request);
        //System.out.print("RequestId=" + response.getRequestId() + "\n");
        Map map = new HashMap();
        if (response.isSuccess()) {
            log.info("imageId=" + response.getImageId());
            log.info("imageURL=" + response.getImageURL());
            log.error("code=" + response.getCode());
            map.put("code",response.getCode());
            map.put("imageId",response.getImageId());
            map.put("imageURL",response.getImageURL());
            return map;
        } else {
            log.error("code=" + response.getCode());
            log.error("ErrorMessage=" + response.getMessage());
            map.put("code",response.getCode());
            map.put("msg",response.getMessage());
            return map;
        }
    }

    /**
     * 提交转码作业
     * @param videoId
     * @return
     */
    public static void submitTranscodeJobs(String videoId){
        DefaultAcsClient client = initVodClient();
        SubmitTranscodeJobsRequest request = new SubmitTranscodeJobsRequest();
        //需要转码的视频ID
        request.setVideoId(videoId);
        //转码模板ID
        request.setTemplateGroupId(templateGroupId);
        try {
            SubmitTranscodeJobsResponse response = client.getAcsResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }
    }

    /**
     * 阿里云转码事件回调函数
     * EventType -> TranscodeComplete
     * @param params
     * @return
     */
    public String StreamTranscodeComplete(@RequestBody Map<String,Object> params){
        String EventType = "";
        String videoId = "";
        String playurl = "";
        /** 视频转码状态，只要有一路流转码成功即为成功，取值：success(成功)，fail(失败) */
        if(params.get("EventType") != null && params.get("EventType") != ""){
            videoId = params.get("VideoId").toString();
            playurl = params.get("FileUrl").toString();
            log.info("转码回调接口返回的视频地址------------>"+playurl);
            Calendar calendar = Calendar.getInstance();
            String logoRealPathDir = "/upload/" + String.valueOf(calendar.get(Calendar.YEAR)) + String.valueOf(calendar.get(Calendar.MONTH) + 1) + String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
            // 创建文件夹
            File logoSaveFile = new File(saveImagePath + logoRealPathDir);
            if (!logoSaveFile.exists()) {
                logoSaveFile.mkdirs();
            }

            String aliyunImageId = "";
            String aliyunImageUrl = "";
        }
        return EventType;
    }
}
